from django.shortcuts import render
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.response import Response
from index.indexserializer import SpeciesSerializer, FoodSerializer, PetAgeSerializer, ActivitySerializer, \
    PetEncyclopediaSerializer
from index.models import SpeciesModel, FoodModel, PetAgeModel, ActivityModel, PetEncyclopediaModel
from elasticsearch import Elasticsearch
import os
import shutil
import uuid


# Create your views here.
# 获取所有物种
class SpeciesView(APIView):
    def get(self, request):
        species = SpeciesModel.objects.all()
        return Response({'data': SpeciesSerializer(species, many=True).data, 'code': 200})

# 获取所有年龄
class PetpecipeView(APIView):
    def get(self, request):
        pet_ages = PetAgeModel.objects.all()
        return Response({'data': PetAgeSerializer(pet_ages, many=True).data, 'code': 200})

    def post(self, request):
        species_id = request.data.get('species_id')
        species = SpeciesModel.objects.filter(id=species_id)
        return Response({'data': SpeciesSerializer(species, many=True).data, 'code': 200})


# 根据食用等级获取猫的食物
class FoodGradeVIew(APIView):
    def get(self, request):
        species_id = request.query_params.get('species_id')
        grade = request.query_params.get('grade')
        foods = FoodModel.objects.filter(species_id=species_id).filter(grade=grade)
        return Response({'data': FoodSerializer(foods, many=True).data, 'code': 200})


# 根据食物分类获取猫的食物
class FoodTypeView(APIView):
    def get(self, request):
        species_id = request.query_params.get('species_id')
        type = request.query_params.get('type')
        foods = FoodModel.objects.filter(species_id=species_id).filter(type=type)
        return Response({'data': FoodSerializer(foods, many=True).data, 'code': 200})


# 根据活动分类获取活动
class ActivityTypeView(APIView):
    def get(self, request):
        species_id = request.query_params.get('species_id')
        type = request.query_params.get('type')
        activities = ActivityModel.objects.filter(type=type)
        data = ActivitySerializer(activities, many=True).data
        for activity in data:
            activity['pet_ages'] = PetAgeSerializer(
                PetAgeModel.objects.filter(species_id=species_id).filter(id__in=activity['pet_ages']), many=True).data
        return Response({'data': data, 'code': 200})


# 根据宠物年龄获取活动
class ActivityAgeView(APIView):
    def get(self, request):
        species_id = request.query_params.get('species_id')
        age = request.query_params.get('age')
        pet_age = PetAgeModel.objects.filter(species_id=species_id).filter(age=age).first().id
        activities = ActivityModel.objects.filter(pet_ages=pet_age)
        data = ActivitySerializer(activities, many=True).data
        for activity in data:
            activity['pet_ages'] = PetAgeSerializer(
                PetAgeModel.objects.filter(id=pet_age), many=True).data
        return Response({'data': data, 'code': 200})



# es上传数据
es = Elasticsearch("http://20.40.103.205:9200/")
class EsAddDataView(APIView):
    def get(self, request):
        # 宠物百科表数据
        encyclopedias = PetEncyclopediaModel.objects.all()

        for i in encyclopedias:
            es.index(index='pet_encyclopedia', body={
                'id': i.id,
                'table_name': 'pet_encyclopedia',
                'title': i.title,
                'content': i.content,
                'read': i.read,
            })

        return Response({'code': 200})


# es搜索数据
class EsSearch(APIView):
    def get(self, request):
        # 获取当前页
        page = request.query_params.get("page")
        if not page:
            page = 1
        # 每页显示多少条
        page_size = 5
        # 搜索内容
        mes = request.query_params.get('mes')
        # 计算开始位置
        start = (int(page) - 1) * page_size

        dsl = {
            "query": {
                "bool": {
                    "should": [
                        {"match": {"title": mes}},
                        {"match": {"content": mes}}
                    ]
                }
            },
            "from": start,
            "size": page_size,
            "_source": ["title", "id"],
            "sort": {
                "read": {
                    "order": "desc"
                }
            }
        }
        res = es.search(index="pet_encyclopedia", body=dsl)
        # print(res)
        data = [i["_source"] for i in res["hits"]["hits"]]
        print(data)
        return Response({'data': data, 'code': 200, 'counts': 10, 'page_size': page_size})


# 百科表分页器
class EncyPagination(PageNumberPagination):
    page_size = 4
    max_page_size = 5
    page_size_query_param = 'size'

# 获取宠物百科表数据
class PetEncyclopediaView(APIView):
    def get(self, request):
        pet_encyclopedia = PetEncyclopediaModel.objects.all()
        ency_page = EncyPagination()
        ency_page_quy = ency_page.paginate_queryset(pet_encyclopedia, request)
        ency_ser = PetEncyclopediaSerializer(ency_page_quy, many=True)
        return Response({'data': ency_ser.data, 'code': 200,
                         'counts': len(pet_encyclopedia), 'page_size': ency_page.page_size})


# 获取单个宠物百科表数据
class PetEncyclopediaDetailView(APIView):
    def get(self, request):
        id = request.query_params.get('id')
        pet_encyclopedia = PetEncyclopediaModel.objects.filter(id=id).first()
        return Response({'data': PetEncyclopediaSerializer(pet_encyclopedia).data, 'code': 200})


def get_folder_size(folder_path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                size = os.path.getsize(fp)
                total_size += size
            except OSError:
                pass  # Ignore files that can't be accessed
    return total_size

# 文件上传
class FileUploadView(APIView):
    def post(self, request):
        data = request.data
        img = data.get('file')
        filename = data['filename']
        tcount = int(data['tcount'])
        count = int(data['count'])
        size = int(data['size'])
        fname = uuid.uuid1().hex
        # 上传代码 os.rename() uuid.uuid().hex
        arr = filename.split('.')
        filepath = f'./static/{filename}'
        if not os.path.exists(filepath):
            os.mkdir(f'./static/{filename}')

        with open(f'./static/{filename}/{count}', 'wb') as f:
            for chunk in img.chunks():
                f.write(chunk)
                # f.close()
        fsize = get_folder_size(filepath)
        if size == fsize:
            # 合并
            with open(f'./static/{fname}.{arr[1]}', 'wb') as f:
                for i in range(tcount):
                    with open(f'./static/{filename}/{i}', 'rb') as chunk:
                        f.write(chunk.read())
            # 删除文件夹
            # if os.path.exists(filepath):
            #     shutil.rmtree(filepath)

            return Response({"code": 200})
        else:
            return Response({"code": 10010})